"use client";
import BackButton from "@/components/BackButton";
import useTask from "../../../useTask";
import { Button, Input, message, Rate } from "antd";
import { useApolloClient, useMutation } from "@apollo/client";
import { useCallback, useMemo, useState } from "react";
import { CommentTaskItemMutation } from "@/queries/task";
import { gqlError } from "@/libs/apollo-errors";

const UserTaskTeacherTaskPage = ({ params: { id, teacher_id } }) => {
  const taskId = parseInt(id);
  const teacherId = parseInt(teacher_id);
  const client = useApolloClient();
  const { taskItems, teachers, entity, getTeacherDetail } = useTask(taskId);
  const { teacherCommon, teacherItem } = useMemo(
    () => getTeacherDetail(teacherId),
    [getTeacherDetail]
  );

  const [push, { loading }] = useMutation(CommentTaskItemMutation, {
    onCompleted() {
      message.success("提交成功");
      client.resetStore();
    },
    onError(error) {
      gqlError(error);
    },
  });
  const [state, setState] = useState<
    {
      name: string;
      comment: string;
      id: number;
      rate: number;
    }[]
  >([]);
  const [common, setCommon] = useState("");
  useMemo(() => {
    setCommon(teacherCommon);
    setState(
      taskItems.map(({ name, comment, id }) => {
        return {
          name,
          comment,
          id,
          rate: teacherItem?.find((e) => e.taskItemId === id)?.score || 0,
        };
      })
    );
  }, [taskItems, teacherItem, teacherCommon]);
  const currentTeacher = teachers.find(
    (teacher) => teacher.id === Number(teacher_id)
  );
  const isReadOnly = !entity?.status || !!teacherItem?.length;

  const onSubmit = useCallback(() => {
    if (state.some((e) => !e.rate)) {
      message.error("必填项不得为空");
      return;
    }
    push({
      variables: {
        id: taskId,
        teacherId,
        common,
        rates: state.map(({ id, rate }) => ({ id, rate })),
      },
    });
  }, [state, common]);
  return (
    <div className="space-y-6">
      <BackButton />
      <h1 className="text-2xl font-bold">{entity?.title}</h1>
      {currentTeacher && (
        <h2 className="text-xl font-semibold">
          相关教师: {currentTeacher.name}
        </h2>
      )}
      {state.map((item, index) => (
        <div key={item.id} className="border p-4 rounded-md">
          <h3 className="text-lg font-medium mb-2">{item.name}</h3>
          <p className="text-gray-600 mb-4">{item.comment}</p>
          <Rate
            allowHalf
            disabled={isReadOnly}
            value={item.rate}
            onChange={(value) => {
              setState((prev) => {
                prev[index].rate = value;
                return [...prev];
              });
            }}
          />
        </div>
      ))}

      {isReadOnly && (
        <p className="text-red-500 font-semibold">此评价已结束，无法修改</p>
      )}
      {!isReadOnly && (
        <div>
          <div className="border p-4 rounded-md">
            <h3 className="text-lg font-medium mb-2">其他建议(可选)</h3>
            <p className="text-gray-600 mb-4">
              您有任何其他的建议，都可以向我们反馈
            </p>
            <Input.TextArea
              value={common}
              onChange={(e) => setCommon(e.target.value)}
            />
          </div>
          <Button loading={loading} className="mt-2" onClick={onSubmit}>
            提交
          </Button>
        </div>
      )}
    </div>
  );
};
export default UserTaskTeacherTaskPage;
